<template>
	<div style=" padding: 20px 0px;
    width: 78%;
    display: flex;
    align-items: center;
    flex-flow: column;
    height: 100vh;
    justify-content: center;
}">

		<div class="chatBig">
			<div class="chatBox" style="" ref="contentContainer">

				<div class="" v-for="(item,index) in chatArr">
					<div style="" :class="{'ctFor1':item.name=='ai','ctFor2':item.name=='me'}">
						<img class="headImg" width="50" height="50"
							:src="item.name=='ai'?require('../assets/logo.png'):require('../assets/ai2.png')  " alt="" />
						<div class="" style="display:flex;flex-flow:row;align-items:center;}">
							<el-image v-if="item.img&&item.name=='me'"
							    style="width: 40px; height: 40px;margin-right: 20px;"
							    :src="item.img" 
							    :preview-src-list="[item.img]">
							  </el-image>
					<!-- 		<img style="margin-right: 20px;" v-if="item.img&&item.name=='me'" width="40" height="40" :src="item.img"
								alt="" srcset="" /> -->
							<div v-if="item.name=='me'" v-html="item.query" class="xjT2"> </div>
						</div>

						<div class="" style="display:flex;flex-flow:row-reverse;align-items:center;}">
							<el-image v-if="item.img&&item.name=='ai'" 
							    style="width: 40px; height: 40px;margin-left: 20px;"
							    :src="item.img" 
							    :preview-src-list="[item.img]">
							  </el-image>
							<!-- <img style="margin-left: 20px;" v-if="item.img&&item.name=='ai'" width="40" height="40" :src="item.img"
								alt="" srcset="" /> -->
							<div v-if="item.query&&item.name=='ai'" v-html="item.query" class="xjT"></div>
						</div>



						
						<div v-if="!item.query&&item.name=='ai'" class="xjT">思考中<i class="el-icon-loading"></i></div>
					</div>
				</div>

			</div>
			<div style=" width: 720px; background: #fff;padding: 0 15px; display: flex; flex-flow: column; justify-content: right; margin: 0 auto;position: absolute; bottom: 0; "
				class="">
				<div class="top" style="border-bottom: 1px solid #e8e8e8;height: 40px;">
					<label for="uploadImage" class="uploadImage"><el-tooltip style="margin-right: 10px;"
							popper-class="tps" class="item" effect="dark" content="上传图片" placement="top">
							<img class="scTp" width="18" src="../assets/img1.png" alt="" srcset="" />
						</el-tooltip>
					</label>
					<input type="file" name="image" value="" id="uploadImage" accept="image/*" hidden="hidden"
						@change="handleFileChange">
					<label for="uploadDocument" class="uploadImage"><el-tooltip style="margin-right: 10px;"
							popper-class="tps" class="item" effect="dark" content="上传文档" placement="top">
							<img class="scTp" width="18" src="../assets/shangchuan.png" alt="" srcset="" />
						</el-tooltip>
					</label>
					<input type="file" name="image" value="" id="uploadDocument" hidden="hidden"
						accept=".doc,.pdf,.docx" @change="handleFileUpload">




				</div>
				<div class="bottom" :style="{'height':isLoading?'50px':'' }">
					<div v-if="imageUrl" class="image-container" @mouseover="showClose = true"
						@mouseout="showClose = false">

						<img v-if="imageUrl" width="40" height="40" :src="imageUrl" alt="File Preview">
						<button v-show="showClose" @click="removeImage" class="close-button ">✕</button>

					</div>

					<div v-if="uploadedFile" style="margin: 10px 0px;">

						<span
							style="padding: 10px;background: #d5e8f9;border-radius: 10px;font-size: 14px;position: relative;"
							@mouseover="showClose2 = true" @mouseout="showClose2 = false">{{ uploadedFile.name }}<button
								v-show="showClose2" @click="removeDocument" class="close-button ">✕</button></span>



					</div>
					<div v-if="isLoading" class="loading-icon">
						<!-- 这里可以放置你的 loading 图标或动画 -->
						<i class="el-icon-loading"></i>
					</div>
				</div>
				<textarea @keyup.enter="sendChat()" v-model="chatForm.query" placeholder="输入你想解决的问题"
					style="resize: none;width: 100%;border: none;outline-style: none;font-size: 16px;padding-top: 10px; "
					rows="4" cols="50">

				</textarea>
				<input class="send" style="" type="submit" value="Go" @click="sendChat()" />
			</div>

		</div>


	</div>

	</div>
</template>

<script>
	import MarkdownIt from 'markdown-it'
	import {
		getChat,
		uploadDocument,
		uploadImg,
		chatAndImg,
		getChatByDocument
	} from '../api/chat.js'
	export default {
		name: 'DataAnalysis', // 请将ComponentName替换为实际的组件名，例如DataAnalysis  
		props: {
			message: {
				type: Object,
				required: true
			}
		},

		data() {
			return {
				isLoading: false,
				chatArr: [{
					name: 'ai',
					query: '你好，我是星链天地开发的智能AI助理！'
				}, ],
				chatForm: {
					query: "",
					conversation_id: "",
					history_len: -1,
					history: [],
					stream: false,
					model_name: "Qwen1.5-1.88-Chat",
					temperature: 0.7,
					max_tokens: 0,
					prompt_name: "default",

				},
				originalText: "",
				myChat: '',
				typingIndex: 0,
				typingInterval: null,

				uploadedFile: null,
				imageUrl: null,
				showClose: false,
				showClose2: false,
				fileList: [{
					name: 'food.jpeg',
					url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
				}, {
					name: 'food2.jpeg',
					url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
				}]
			};
		},
		methods: {
			//清空对话
			clear() {
				this.chatArr = [{
					name: 'ai',
					query: '你好，我是星链天地开发的智能AI助理！'
				}]
				console.log(5555858)
				this.removeDocument()
				this.removeImage()
			},

			// 滚动到底部的函数
			scrollToBottom() {
				const container = this.$refs.contentContainer;
				container.scrollTop = container.scrollHeight;
			},
			sendChat() {
				const isEmptyOrSpacesOnly = /^\s*$/.test(this.chatForm.query);
				if (isEmptyOrSpacesOnly) {
					this.$message({
						message: '请输入内容！',
						type: 'warning'
					});
				} else {
					//判断是聊天还是图片还是文档
					this.chatArr.push({
						img: this.imageUrl ? this.imageUrl : '',
						name: 'me',
						query: this.chatForm.query
					})
					this.chatArr.push({
						name: 'ai',
						query: ''
					})
					this.$nextTick(() => {

						this.scrollToBottom()
					})
					console.log(this.chatArr)


					if ((this.imageUrl || this.uploadedFile) && !this.isLoading) {

						if (this.imageUrl) {
							//进入图片的分析中
							let obj = {
								q: this.chatForm.query,
								img_id: this.chatForm.img_id
							}
							chatAndImg(obj).then((res) => {
								if (res.img_url) {

									this.chatArr[this.chatArr.length - 1].img = res.img_url
									console.log('有图片')
								}
								this.originalText = res.msg
								this.startTyping()
							})



						} else if (this.uploadedFile) {
							//进入文档的分析中
							let obj = {
								query: this.chatForm.query,
								knowledge_id: this.chatForm.knowledge_id,
								top_k: 3,
								score_threshold: 1,
								stream: false,
								model_name: "Qwen1.5-1.8B-Chat",
								temperature: 0.7,
								max_tokens: 0,
								prompt_name: "default"
							}
							console.log(obj)
							getChatByDocument(obj).then((res) => {
								let subStr = res.substring(5);
								subStr = JSON.parse(subStr).answer
								let strForHTML = JSON.stringify(subStr.replace(/\n/g, '<br>'));
								this.originalText = strForHTML
								// this.originalText = new MarkdownIt().render(subStr)
								this.startTyping()
							})

						} else {

						}

					} else if (this.isLoading) {
						this.$message({
							message: '文件上传中，请稍等！',
							type: 'warning'
						});

					} else {
						// alert('纯聊天')
						let obj = {
							query: this.chatForm.query,

							stream: false,
							model_name: "Qwen1.5-1.8B-Chat",
							temperature: 0.7,
							max_tokens: 0,
							prompt_name: "default",

						}
						getChat(obj).then((res) => {

							let subStr = res.substring(5);
							subStr = JSON.parse(subStr).text
							let strForHTML = JSON.stringify(subStr.replace(/\n/g, '<br>'));
							this.originalText = strForHTML
							// this.originalText = new MarkdownIt().render(subStr)
							this.startTyping()
							console.log(res)

						})
					}
				}
				this.chatForm.query = ''
				this.typingIndex = 0

				return





				// console.log(this.message)

				return



			},
			handleFileChange(event) {
				this.removeDocument()
				console.log(event)
				this.isLoading = true
				const file = event.target.files[0];
				if (file && file.type.startsWith('image/')) {
					const reader = new FileReader();

					const formData = new FormData();
					formData.append('file', file);
					uploadImg(formData).then((res) => {
						if (res.img_id) {
							this.chatForm.img_id = res.img_id

							this.isLoading = false
							reader.onload = (e) => {
								console.log(e)
								this.imageUrl = e.target.result;
							};
							reader.readAsDataURL(file);
							event.target.value = ''
						}
					})
				}
			},
			handleFileUpload(event) {
				this.removeImage()
				this.isLoading = true
				const formData = new FormData();
				const file = event.target.files[0];
				console.log(event.target.files)
				if (file) {
					console.log(55555)
					formData.append('files', file);
					formData.append('chunk_size', 250);
					formData.append('prev_id: ', '');
					formData.append('chunk_overlap', 50);
					formData.append('zh_title_enhance', false);
					uploadDocument(formData).then((res) => {
						if (res.code == 200) {
							if (this.message.dhMsValue = 'file_chat') {
								this.uploadedFile = file;
								this.chatForm.knowledge_id = res.data.id
								this.chatForm.score_threshold = 1
								this.isLoading = false
							}
						}

					})
				}
			},
			removeImage() {
				if (this.uploadedFile) {
					this.uploadedFile = '';
				} else {

					this.imageUrl = ''; // 清除图片URL，图片和删除按钮将不再显示  
					this.showClose = false; // 确保删除按钮被隐藏  
					// 如果需要，可以在这里添加额外的删除逻辑，比如从服务器删除图片等  
					this.message.img_id = ''
					this.isLoading = false
				}

			},
			removeDocument() {
				if (this.imageUrl) {
					this.imageUrl = ''; // 清除图片URL，图片和删除按钮将不再显示
					this.showClose = false; // 确保删除按钮被隐藏  
					this.message.img_id = ''
				} else {
					this.uploadedFile = '';
				}

			},
			startTyping() {
				// 清除之前的打字间隔  
				clearInterval(this.typingInterval);

				// 开始新的打字间隔  
				this.typingInterval = setInterval(() => {
					// 如果已经打完了所有的字，就停止打字  
					if (this.typingIndex >= this.originalText.length) {
						clearInterval(this.typingInterval);
					} else {
						// 否则，每次添加一个字符  
						let lastObject = this.chatArr[this.chatArr.length - 1];
						lastObject.query += this.originalText[this.typingIndex++];
					}
					this.scrollToBottom()
				}, 10); // 这里设置打字速度为每100毫秒一个字符  
			}





		},
		mounted() {

		},
		created() {

		}
	};
</script>

<style scoped lang="scss">
	.headImg {
		object-fit: fill;
		border-radius: 15px;
	}

	.ctFor1 {
		display: flex;
		padding: 0 20px;
		margin-bottom: 10px;
	}

	.ctFor2 {
		display: flex;
		flex-flow: row-reverse;
		padding: 0 20px;
		margin-bottom: 10px;
	}

	.chatBig {
		height: 670px;
		width: 750px;
		padding: 20px 0;
		/* background: rgb(87 87 87 / 39%); */
		margin-bottom: 10px;
		overflow: auto;
		border: 1px solid rgb(87 87 87 / 39%);
		border-radius: 20px;
		position: absolute;
		box-shadow: 1px 1px 10px #ccc;
	}



	.image-container {
		position: relative;
		display: inline-block;
		cursor: pointer;
		/* 添加鼠标悬停样式 */
	}

	.close-button {
		position: absolute;
		top: -5px;
		right: -5px;
		background-color: #ccc;
		color: white;
		border: none;
		cursor: pointer;
		padding: 2px;
		width: 15px;
		height: 15px;
		border-radius: 20px;
		opacity: 0.8;
		align-items: center;
		line-height: 10px;
		/* 初始透明度 */
		transition: opacity 0.3s ease;
		/* 添加过渡效果 */
	}

	.image-container:hover .close-button {
		opacity: 1;
		/* 鼠标悬停时增加透明度 */
	}


	.top {
		display: flex;
		flex-flow: row;
		align-items: center;
		transition: transform 0.3s ease-in-out;
	}

	.scTp {
		padding: 5px;
	}

	.scTp:hover {
		cursor: pointer;
		background: #e3e3e3;
		padding: 5px;
		border-radius: 8px;
		transform: scale(1.1);

	}






	textarea::placeholder {
		color: #b5b4b4;
		/* 或者你想要的任何颜色 */
		opacity: 1;
		/* Firefox */
	}

	input {
		transition: transform 0.3s ease-in-out;
		/* 添加过渡效果，持续时间为0.3秒 */
	}

	input:hover {
		cursor: pointer;
		background: linear-gradient(57deg, #30d2ff, #496cde) !important;
		transform: scale(1.1);
	}

	.tps.el-tooltip__popper {
		background: linear-gradient(57deg, #8c8ef7, #3c73e9);
	}

	.el-tooltip__popper[x-placement^="top"] .popper__arrow:after,
	.el-tooltip__popper[x-placement^="top"] .popper__arrow {
		border-top-color: #8c8ef7;
		opacity: 0.5;
	}

	.send {
		margin-left: 92%;
		margin-bottom: 10px;
		background: linear-gradient(57deg, #8c8ef7, #3c73e9);
		outline: none;
		border: none;
		height: 35px;
		border-radius: 20px;
		color: #fff;
		width: 50px;
	}

	.chatBox {
		overflow: auto;
		width: 100%;
		height: 470px;
	}

	.chatBox::-webkit-scrollbar {
		display: none;
		/* 隐藏滚动条 */
	}

	.xjT,
	.xjT2 {
		position: relative;
	}


	.xjT {
		margin-left: 20px;
		color: #fff;
		background: #5b6669;
		padding: 16px 5px;
		border-radius: 10px;
	}

	.xjT {
		p {
			margin: 0;
		}
	}

	.xjT2 {
		margin-right: 20px;
		color: #fff;
		background: #2fdb6c;
		padding: 16px 5px;
		border-radius: 10px;
	}


	.xjT:before {
		content: "";
		width: 10px;
		height: 0px;
		border-top: 10px solid transparent;
		border-bottom: 10px solid transparent;
		border-right: 10px solid #5b6669;
		position: absolute;
		top: 12px;
		left: -20px;
	}

	.xjT2:before {
		content: "";
		width: 10px;
		height: 0px;
		border-top: 10px solid transparent;
		border-bottom: 10px solid transparent;
		border-left: 10px solid #2fdb6c;
		position: absolute;
		top: 12px;
		right: -20px;
	}

	.loading-icon {
		border: 5px solid #f3f3f3;
		border-top: 5px solid #3498db;
		border-radius: 50%;
		width: 25px;
		height: 25px;
		animation: spin-4aede454 2s linear infinite;
		position: absolute;
		top: 3px;
		left: 3px;
		text-align: center;
		line-height: 25px;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.bottom {
		position: relative;
	}
</style>